<template>
  <div v-if="payInfo" class="home-cashier-wrap">
    <van-nav-bar title="收银台" left-arrow fixed @click-left="onClickLeft" />

    <div class="pay-price">{{ payInfo.title }}</div>
    <!-- 出现了精度问题 -->
    <div class="pay-val">{{ (Number(payInfo.amount_text) + Number(payInfo.deduction_xjq)).toFixed(2) }}</div>
    <div class="pay-time">
      {{ payInfo.expired_desc }}
      <van-count-down :time="payInfo.expired_seconds * 1000" @finish="finish" />
    </div>

    <!-- 支付方式 v-if="payInfo.coupon_payed > 0" -->
    <div class="pay-methods">
      <div v-if="deduction_list.length > 0">
        <div class="youhui_pay" v-for="(item, index) in deduction_list" :key="index">
          <div>{{ item.title }}</div>
          <div>
            {{ item.content }}
          </div>
        </div>
      </div>
      <div v-for="(item, index) in payInfo.methods" :key="index" @click="handleToChange(index)" class="pay-methods-li">
        <img class="pay-methods-li-icon" :src="item.icon" alt="" />
        <div class="pay-desc">
          <div class="pay-desc-name">{{ item.title }}</div>
          <div class="pay-desc-info">{{ item.desc }}</div>
        </div>

        <img class="pay-select" :src="current === index ? defaultTagIcon : defaultCircle" alt="" />
      </div>
    </div>

    <div @click="handleToPay" class="btn-pay active-btn">
      {{ payInfo.methods[current].button_text }}
    </div>

    <!-- 余额支付 -->
    <balance-pay-popup v-if="showPayPopup" ref="transferPayPopup" @refreshData="handleRefreshData"></balance-pay-popup>
  </div>
</template>

<script>
import { ORDER_PAY } from '@/api/home'
import { ORDER_CREATE, WX_PAY } from '@/api/mine'
import { defaultCircle, defaultTagIcon } from '@/tool/static-img'
import balancePayPopup from './components/balance-pay-popup'

export default {
  components: {
    balancePayPopup,
  },
  data() {
    return {
      defaultTagIcon,
      defaultCircle,
      order_id: this.$route.query.order_id,
      payInfo: null,
      current: 0,
      // 交易编号，用于支付结果验证
      tradeNo: '',

      // 余额支付
      showPayPopup: false,
      // 抵扣信息
      deduction_list: [],
    }
  },
  created() {
    // 检查localStorage中是否有保存的支付方式选择
    const savedPaymentMethod = localStorage.getItem('selectedPaymentMethod')
    if (savedPaymentMethod !== null) {
      // 如果有保存的支付方式，设置为当前选择
      this.current = parseInt(savedPaymentMethod)
      // 使用完后清除保存的支付方式，避免影响下次选择
      localStorage.removeItem('selectedPaymentMethod')
    }

    // 有订单号参数 按订单号查询
    if (this.order_id) {
      // 子订单 - 可走订单id
      this.getOrderPay()
    } else {
      // 其他走本地传信息
      const cashOrder = JSON.parse(localStorage.getItem('cashOrder'))
      // 确保毫秒级时间戳相减后再转换为秒
      cashOrder.expired_seconds = parseInt((cashOrder.expired_time - new Date().getTime()) / 1000)
      this.payInfo = cashOrder
      this.order_id = cashOrder.business_id
      // 现金券抵扣
      this.deduction_list = cashOrder.deduction_list || []

      // 超时
      if (cashOrder.expired_seconds <= 0) {
        this.$router.replace({ name: 'orderList', })
      }

      // 获取URL授权码
      const auth_code = this.getUrlParam('code')
      console.log('获取URL授权码:', auth_code)
      if (auth_code) {
        // 检查URL中是否有微信支付回调的code参数
        this.checkWechatPayCallback()
        // 拿到code后清理 URL
        this.cleanUrlCode()
      }
    }
  },
  methods: {
    // 检查是否是微信支付回调回来的页面
    checkWechatPayCallback() {
      const code = this.getUrlParam('code')
      if (code) {
        console.log('检测到微信支付回调的code参数:', code)
        // 延迟执行，等待payInfo加载完成
        setTimeout(() => {
          if (this.payInfo) {
            this.createOrderAndPay(code)
          } else {
            // 如果payInfo还没加载完成，先保存code到localStorage
            localStorage.setItem('wechatPayCode', code)
          }
        }, 300)
      } else {
        // 检查localStorage中是否有之前保存的code
        const savedCode = localStorage.getItem('wechatPayCode')
        if (savedCode) {
          localStorage.removeItem('wechatPayCode')
          this.createOrderAndPay(savedCode)
        }
      }
    },
    onClickLeft() {
      this.$router.back()
    },
    getOrderPay() {
      this.$http.get(ORDER_PAY + this.order_id)
        .then((res) => {
          this.payInfo = res.data
          this.payInfo.expired_time = new Date().getTime() + res.data.expired_seconds * 1000;
          // 现金券抵扣
          this.deduction_list = res.data.deduction_list || []
          // 缓存收银台数据
          localStorage.setItem('cashOrder', JSON.stringify(this.payInfo))
        })
        .catch(() => {
          console.log('跳转回到订单列表 OrderPay')
          this.$router.replace({ name: 'orderList', })
        })
    },
    handleToChange(index) {
      this.current = index
      // 保存当前选择的支付方式到localStorage
      localStorage.setItem('selectedPaymentMethod', this.current)
    },
    finish() {
      this.$router.replace({ name: 'orderList', })
    },
    // 去支付
    handleToPay() {
      if (this.payInfo.methods[this.current].type === 'APP_BALANCE_CASH') {
        // 余额支付
        this.showPayPopup = true
        this.$nextTick(() => {
          this.$refs['transferPayPopup'].initData(this.order_id)
        })
      } else {
        // 判断是否为微信支付
        if (this.payInfo.methods[this.current].type === 'WECHAT') {
          // 保存当前选择的支付方式到localStorage，以便从微信授权页面返回时恢复
          localStorage.setItem('selectedPaymentMethod', this.current)

          // 微信支付：先调用接口获取授权URL
          this.$http.post(WX_PAY, { redirect_uri: location.href.split('#')[0] + '#/cashier', })
            .then((authRes) => {
              // 获取授权URL
              console.log('authRes', authRes.data.auth_url)
              // 跳转到微信授权页面
              location.href = authRes.data.auth_url
            })
            .catch((error) => {
              console.error('获取微信支付授权码失败:', error)
              this.$toast('微信授权失败，请重试')
            })
        } else {
          // 其他支付方式
          this.createOrderAndPay()
        }
      }
    },

    // 从URL中提取参数的辅助函数
    getUrlParam(name) {
      const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
      const r = window.location.search.substr(1).match(reg)
      if (r != null) {
        return unescape(r[2])
      }
      return null
    },

    // 清理 URL 中的 code 参数
    cleanUrlCode() {
      const { href } = window.location
      // 分割 URL 为「查询参数部分」和「哈希部分」（避免哈希被误处理）
      const [urlWithoutHash, hash = ''] = href.split('#')
      // 1. 清理查询参数中的 code 和 state
      let cleanUrlWithoutHash = urlWithoutHash
      // 正则匹配并删除所有 code=xxx& 或 state=xxx&（处理重复参数）
      cleanUrlWithoutHash = cleanUrlWithoutHash.replace(/([&?])code=[^&]+&?/g, '$1')
      cleanUrlWithoutHash = cleanUrlWithoutHash.replace(/([&?])state=[^&]+&?/g, '$1')
      // 去除末尾可能残留的 & 或 ?
      cleanUrlWithoutHash = cleanUrlWithoutHash.replace(/[&?]$/, '')
      // 2. 重组 URL（干净的路径 + 保留的哈希）
      const cleanHref = `${cleanUrlWithoutHash}${hash ? '#' + hash : ''}`
      // 3. 替换当前 URL（不新增历史记录）
      if (cleanHref !== href) {
        window.history.replaceState(null, null, cleanHref)
      }
    },

    // 创建订单并支付
    createOrderAndPay(code) {
      // 确保有授权code
      if (!code) {
        code = this.getUrlParam('code')
      }

      let params = {
        business_id: this.payInfo.business_id,
        business_type: this.payInfo.business_type,
        price: this.payInfo.amount,
        channel_id: this.payInfo.methods[this.current].type,
        product_code: this.payInfo.methods[this.current].product_code,
        return_url: location.href.split('#')[0] + '#/payResult',
        auth_code: code, // 使用从URL中提取的真实code作为auth_code
      }
      this.$http.post(ORDER_CREATE, params).then((res) => {
        // 无论支付方式如何，都先保存trade_no到实例属性中
        this.tradeNo = res.data.trade_no

        // 如果是微信支付
        if (res.data.channel_id === 'WECHAT') {
          // 调用微信支付 JSAPI
          this.handleWechatJsapi(res.data.payment_data)
        } else if (res.data.payment_data.startsWith('http')) {
          // 保存订单信息到本地存储
          let data = {
            trade_no: res.data.trade_no, // 校验订单成功与否
            order_id: this.$route.query.order_id ? this.order_id : '', // 判断是单订单还是多订单,用与支付失败再次发起支付用
            business_type: this.payInfo.business_type,
            pay_title: this.payInfo.methods[this.current].title,
            price: this.payInfo.amount,
          }
          localStorage.setItem('orderResult', JSON.stringify(data))
        }
      })
    },
    // 余额支付结束
    handleRefreshData() {
      let data = {
        business_type: this.payInfo.business_type,
        pay_title: this.payInfo.methods[this.current].title,
        price: this.payInfo.amount,
      }
      localStorage.setItem('orderResult', JSON.stringify(data))
      this.$router.replace({
        name: 'payResult',
        query: {
          status: 1,
        },
      })
    },
    // 微信JSAPI支付
    handleWechatJsapi(payment_data) {
      if (typeof WeixinJSBridge === 'undefined') {
        // 非微信内置浏览器，直接跳转
        location.href = payment_data
      } else {
        // 微信内置浏览器，使用JSBridge调起支付
        try {
          WeixinJSBridge.invoke('getBrandWCPayRequest', { ...payment_data, },
            function (res) {
              // 支付成功回调
              if (res.err_msg === 'get_brand_wcpay_request:ok') {
                this.$toast('支付成功')
                // 保存订单信息到localStorage，确保支付结果页面能显示数据
                let data = {
                  business_type: this.payInfo.business_type,
                  pay_title: this.payInfo.methods[this.current].title,
                  price: this.payInfo.amount,
                  trade_no: this.tradeNo, // 使用正确的交易编号用于验证
                  order_id: this.$route.query.order_id ? this.order_id : '' // 添加订单ID
                }
                localStorage.setItem('orderResult', JSON.stringify(data))
                // 跳转并添加status=1参数表示支付成功
                location.href = location.href.split('#')[0] + '#/payResult?status=1'
              } else {
                // 支付失败处理
                this.$toast('支付失败，请重试')
              }
            }.bind(this)
          )
        } catch (e) {
          // 异常情况下也直接跳转
          console.error('微信支付调用异常:', e)
          location.href = payment_data
        }
      }
    },
  },
}
</script>
<style lang="scss">
.home-cashier-wrap {
  position: relative;
  min-height: 100vh;
  padding-top: 46px;
  background-color: #f4f4f4;
  padding-bottom: calc(1.2rem + constant(safe-area-inset-bottom));
  padding-bottom: calc(1.2rem + env(safe-area-inset-bottom));
  box-sizing: border-box;

  .van-nav-bar .van-icon {
    color: #333333;
  }

  .van-nav-bar__arrow {
    font-size: 20px;
  }

  .van-hairline--bottom::after {
    display: none;
  }

  .pay-price {
    height: 0.44rem;
    margin-top: 0.72rem;
    font-weight: 500;
    font-size: 0.32rem;
    line-height: 0.44rem;
    text-align: center;
  }

  .pay-val {
    height: 1rem;
    line-height: 1rem;
    font-weight: 500;
    font-size: 0.72rem;
    color: #31a653;
    text-align: center;

    &::before {
      content: "¥";
      font-size: 0.48rem;
    }
  }

  .pay-time {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.28rem;
    color: #999999;

    .van-count-down {
      color: #999999;
    }
  }

  .pay-methods {
    margin-top: 0.88rem;

    .youhui_pay {
      position: relative;
      width: 6.86rem;
      height: 1.44rem;
      margin: auto;
      margin-bottom: 0.24rem;
      border-radius: 0.16rem;
      background: #ffffff;
      padding: 0.32rem;
      box-sizing: border-box;
      background: url("../../images/mine/youhui_bg2.png") no-repeat;
      background-position: center;
      background-size: cover;

      div:first-child {
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 0.32rem;
        color: #333333;
        line-height: 0.44rem;
        text-align: left;
        font-style: normal;
      }

      div:last-child {
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 0.24rem;
        color: #ff6200;
        line-height: 0.34rem;
        text-align: left;
        font-style: normal;
        margin-top: 0.10rem;
      }
    }

    .pay-methods-li {
      position: relative;
      display: flex;
      align-items: center;
      width: 6.86rem;
      height: 1.52rem;
      margin: auto;
      margin-bottom: 0.24rem;
      border-radius: 0.16rem;
      background: #ffffff;

      .pay-select {
        position: absolute;
        right: 0.4rem;
        top: 0;
        bottom: 0;
        margin: auto;
        width: 0.4rem;
        height: 0.4rem;
      }

      .pay-methods-li-icon {
        width: 0.8rem;
        height: 0.8rem;
        margin-left: 0.36rem;
      }

      .pay-desc {
        margin-left: 0.28rem;

        .pay-desc-name {
          height: 0.44rem;
          margin-bottom: 0.06rem;
          line-height: 0.44rem;
          font-weight: 500;
          font-size: 0.32rem;
          color: #333333;
        }

        .pay-desc-info {
          height: 0.34rem;
          line-height: 0.34rem;
          font-weight: 400;
          font-size: 0.24rem;
          color: #999999;
        }
      }
    }
  }

  .btn-pay {
    position: fixed;
    bottom: calc(0.24rem + constant(safe-area-inset-bottom));
    bottom: calc(0.24rem + env(safe-area-inset-bottom));
    left: 0;
    right: 0;
    margin: auto;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 6.86rem;
    height: 0.88rem;
    font-weight: 500;
    font-size: 0.32rem;
    color: #ffffff;
    border-radius: 0.44rem;
    background: linear-gradient(90deg, #75be70 0%, #56ae48 100%);
  }
}
</style>
